package top.blackr.folivora.common.core;

import lombok.*;
import lombok.experimental.Accessors;
import top.blackr.folivora.common.core.enums.ResultEnum;

import java.io.Serial;
import java.io.Serializable;

@Builder
@ToString
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
public class R<T> implements Serializable {

    @Serial
    private static final long serialVersionUID = -3064458689391433130L;

    /**
     * 返回标记
     */
    @Getter
    @Setter
    private int code;

    /**
     * 返回信息
     */
    @Getter
    @Setter
    private String msg;

    /**
     * 数据
     */
    @Getter
    @Setter
    private T data;

    public static <T> R<T> ok() {
        return restResult(null, ResultEnum.SUCCESS);
    }

    public static <T> R<T> ok(T data) {
        return restResult(data, ResultEnum.SUCCESS);
    }

    public static <T> R<T> ok(T data, String msg) {
        return restResult(data, ResultEnum.SUCCESS, msg);
    }

    public static <T> R<T> failed() {
        return restResult(null, ResultEnum.FAIL);
    }

    public static <T> R<T> failed(String msg) {
        return restResult(null, ResultEnum.FAIL, msg);
    }

    public static <T> R<T> failed(T data) {
        return restResult(data, ResultEnum.FAIL);
    }

    public static <T> R<T> failed(ResultEnum resultEnum) {
        return restResult(resultEnum);
    }

    public static <T> R<T> failed(T data, String msg) {
        return restResult(data, ResultEnum.FAIL, msg);
    }

    private static <T> R<T> restResult(T data, ResultEnum code, String msg) {
        R<T> apiResult = new R<>();
        apiResult.setCode(code.getCode());
        apiResult.setData(data);
        apiResult.setMsg(msg);
        return apiResult;
    }

    private static <T> R<T> restResult(T data, ResultEnum code) {
        R<T> apiResult = new R<>();
        apiResult.setCode(code.getCode());
        apiResult.setData(data);
        apiResult.setMsg(code.getCnMes());
        return apiResult;
    }

    private static <T> R<T> restResult(ResultEnum resultEnum) {
        R<T> apiResult = new R<>();
        apiResult.setCode(resultEnum.getCode());
        apiResult.setMsg(resultEnum.getCnMes());
        return apiResult;
    }

}
